package com.stuffthathappens.concurrency;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.ThreadFactory;

/**
 * Use this factory when creating new threads for the entire app. This way we can easily
 * filter our threads by searching for the "sample-" name prefix.
 *
 * @author Eric M. Burke
 */
public class SampleThreadFactory implements ThreadFactory {
    private static final AtomicInteger factoryNumber = new AtomicInteger(1);
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final String prefix;

    public SampleThreadFactory(String baseName) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ?
                s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();

        prefix = "sample-" + baseName + "-factory-" +
                factoryNumber.getAndIncrement() + "-thread-";
    }

    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r, prefix + threadNumber.getAndIncrement(), 0);
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }

        // note: could also register an uncaught exception handler here

        return t;
    }
}